
var formData2Json = function(formData){
    var objData = {};
    //(value, key) => objData[key] = value
    formData.forEach(function (curValue,index,arr) {
        objData[index] = curValue;
    });
    //转json字符串
    //return JSON.stringify(objData);
    //转json对象.
    var objDataStr = JSON.stringify(objData)
    return JSON.parse(objDataStr);
}

var deleteNameFormData = function (formData,Arr) {
    Arr.forEach(function(value,i){
        formData.delete(value);
    });
    return formData;
}
function closeWin(){
    //有关闭确认
    //if(confirm("您确定要关闭本页吗？")){
    window.opener=null;
    window.open('','_self');
    window.close();
    //}
}

var Huitextarealength = function (obj){
    var html = $(obj).parent();
    var tatal = html.find('am').html();
    var sets = $(obj).val().length;

    if(sets*1>tatal*1){
        if($("#contentOverruns").html()==''||$("#contentOverruns").html()==null){
            var str = '<div id="contentOverruns" style="width: auto;position: absolute; right: 10px;color: red;bottom: -4px;">内容超出限制</div>';
            $(obj).after(str);
            html.find('em').css({color:'red'});
        }
    }else {
        $(obj).parent().find('div').remove();
        html.find('em').css({color:'black'});
    }
    //设置已输入数量
    html.find('em').html(sets);
}

var isTrue = function(str){
    if (trim(str) == 'true'){
        return true;
    } else {
        return false;
    }
}

//去掉所有空格
function trim(str) {
    return str.replace(/\s+/g,"");
}

//判断str ，在数组strs中是否存在
function isExist(str ,strs){
    for (var i=0;i<strs.length;i++){
        if (str == strs[i]){
            return true;
        }
    }
    return false;
}

function checkPhone(phone){
    if((/^1[34578]\d{9}$/.test(phone))){
        return true;
    }else{
        //alert("手机号码有误，请重填");
        return false;
    }
}

function isRealNum(val){
    // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除
    if(val === "" || val ==null){
        return false;
    }
    if(!isNaN(val)){
        return true;
    }else{
        return false;
    }
}

//大于0小于1的小数
function g0l1(val){
    if(!isRealNum(val)){
        return false;
    }
    if ((val>0 && val<=1)){
        return true;
    }else {
        return false;
    }
}

//大于start小于end的小数
function countLimit(val,start,end){
    if(!isRealNum(val)){
        return false;
    }
    if ((val>start && val<=end)){
        return true;
    }else {
        return false;
    }
}

//自定义文件格式
var file_type1 = ["jpg","png","tif","gif","webp","jpeg"];
var file_type2 = ["doc","docx"];
var file_type3 = ["xls","xlsx"];
var file_type4 = ["pdf"];
var file_type5 = ["txt"];
var file_allType = ["jpg","png","tif","gif","webp","jpeg","doc","docx","xls","xlsx","pdf","txt"];

var fileLimit = function(obj,fileType,fileSize){

    var result = {};
    var flag = true;
    var fileName = obj.name;
    var filepreffix = fileName.substring(0,fileName.lastIndexOf("."));

    if (hasSpecialChar(filepreffix)){
        //layer.msg('图片名含有特殊符号，请修改后上传。', {icon: 5,time:1500});
        result.result = '图片名含有特殊符号，请修改后上传。';
        result.bool = false;
        return result;
    }

    var filesuffix = fileName.substring(fileName.lastIndexOf(".")+1);

    var file_Size = obj.size;

    //判断file 类型
    var flag1 = false;
    for(var i=0;i<fileType.length;i++){
        if (fileType[i] == filesuffix.toLocaleLowerCase()){
            flag1 = true;
        }
    }

    if(!flag1){
        flag = false;
        result.result = "请上传"+ fileType +"等格式文件。";
    }

    //比较文件大小
    if (file_Size > fileSize){
        flag = false;
        result.result = "文件过大！";
    }
    result.bool = flag;
    return result;

}

function hasSpecialChar(fileName){
    var regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im,
        regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;

    if(regEn.test(fileName) || regCn.test(fileName)) {
        return true;
    }else{
        return false;
    }
}

function deleteFile(obj,op,url,id,attribute){
    if (op == "add"){
        delFileInAddPage(obj,op,url,id);
    }else if(op == "editFile") {
        EditDelFile(obj,op,url,id);
    }else{
        EditDelColumn(obj,op,url,id,attribute);
    }
}

function statistics(ctx ,itemId,url,isDetail){
    //初始化第一页数据
    console.log("IP: " + returnCitySN['cip'] + "<br>地区代码: " + returnCitySN['cid'] + "<br>所在地: " + returnCitySN['cname']);
    var area = returnCitySN['cname'];
    var areaCode = returnCitySN['cid'];
    var IP = returnCitySN['cip'];
    var BI = getBrowserInfo();
    var device = BI.device;
    var bowser = BI.browser + "(" + BI.ver + ")";
    var parms = {"item_id":itemId,"IP":IP,"device":device,"bowser":bowser,"area":area,"areaCode":areaCode};
    console.log(top.location.href);
    var suffix = top.location.href.split("?")[1];
    if (suffix == undefined || !isExist("hmsr",suffix.split("="))){
        suffix = "hmsr=undefined";
    }else{
        suffix = suffix.split("&")[0];
    }
    if (isDetail == "yes"){
        location.href = ctx + '/mobile/productList/showProductDetail/'+itemId;
    } else{
        $.ajax({
            type: 'POST',
            url: ctx + '/mobile/productList/addCuItemPVUV?'+suffix,
            data: parms,
            dataType: 'json',
            cache:false,
            async:true,//异步
            success: function (data) {
                //拼凑html
                if (data.isSuccess == true){
                    console.log("statistics success!!!");
                    //top.location.href = url;

                    window.open(url);
                } else if (data.isSuccess == false && data.result == "redirect") {
                    location.href = ctx + "/mobile/productList/showTelLogin";
                }else {
                    console.log("statistics failed!!!");
                }
            },
            error:function (data) {
                layer.msg('系统错误，请联系管理员！', {icon: 5,time:1500});
                window.open(url);
                console.log(data);
            }
        });
    }

}


function statisticsDetail(ctx ,itemId,url){
    //初始化第一页数据
    console.log("IP: " + returnCitySN['cip'] + "<br>地区代码: " + returnCitySN['cid'] + "<br>所在地: " + returnCitySN['cname']);
    var area = returnCitySN['cname'];
    var areaCode = returnCitySN['cid'];
    var IP = returnCitySN['cip'];
    var BI = getBrowserInfo();
    var device = BI.device;
    var bowser = BI.browser + "(" + BI.ver + ")";
    var parms = {"item_id":itemId,"IP":IP,"device":device,"bowser":bowser,"area":area,"areaCode":areaCode};
    console.log(top.location.href);
    var suffix = top.location.href.split("?")[1];
    if (suffix == undefined || !isExist("hmsr",suffix.split("="))){
        suffix = "hmsr=undefined";
    }else{
        suffix = suffix.split("&")[0];
    }
    $.ajax({
        type: 'POST',
        url: ctx + '/mobile/productList/addCuItemPVUV?'+suffix,
        data: parms,
        dataType: 'json',
        cache:false,
        async:true,//异步
        success: function (data) {
            //拼凑html
            if (data.isSuccess == true){
                console.log("statistics success!!!");
                //top.location.href = url;
                window.open(url);
            } else if (data.isSuccess == false && data.result == "redirect") {
                location.href = ctx + "/mobile/productList/showTelLogin";
            }else {
                console.log("statistics failed!!!");
            }
        },
        error:function (data) {
            window.open(url);
            console.log(data);
        }
    });

}

//判断是否是微信浏览器的函数
function isWeiXin(){
    //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
    var ua = window.navigator.userAgent.toLowerCase();
    //通过正则表达式匹配ua中是否含有MicroMessenger字符串
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}

function getBrowserInfo(){
    var Sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var re =/(msie|firefox|chrome|opera|version|micromessenger).*?([\d.]+)/;
    var m = ua.match(re);
    if (m != null){
        Sys.browser = m[1].replace(/version/, "safari");
        Sys.ver = m[2];
        Sys.device = ua.substring(ua.indexOf("(")+1 ,ua.indexOf(")"));
    }else {
        Sys.browser = "未知";
        Sys.ver = "1.0";
        Sys.device = "Device";
    }
    return Sys;
}


var browser={
    versions:function(){
        var u = window.navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/)||!!u.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
            iPad: u.indexOf('iPad') > -1, //是否为iPad
            webApp: u.indexOf('Safari') == -1 ,//是否为web应用程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') == -1 //是否为微信浏览器
        };
    }()
};

/*document.writeln(" 是否为移动终端: "+browser.versions.mobile);
document.writeln(" ios终端: "+browser.versions.ios);
document.writeln(" android终端: "+browser.versions.android);
document.writeln(" 是否为iPhone: "+browser.versions.iPhone);
document.writeln(" 是否iPad: "+browser.versions.iPad);
document.writeln(navigator.userAgent);*/

function getDate(num) {
    if (num == undefined || num == null)
        num = 0;
    var date = new Date();
    date.setDate(date.getDate() + num);
    var day = date.getDate();
    if (day < 10){
        day = "0" + day;
    }
    var month = date.getMonth() + 1;
    if (month < 10){
        month = "0" + month;
    }
    var year = date.getFullYear();
    return year + "-" + month + "-" + day;
}

function getDateTime(){
    return getDate() + getTime();
}

function getTime(){
    var date = new Date();

    var h = date.getHours();
    if (h<10){
        h = "0" + h;
    }
    var m = date.getMinutes();
    if (m<10){
        m = "0" + m;
    }
    var s = date.getSeconds();
    if (s<10){
        s = "0" + s;
    }

    return h + ":" + m + ":" + s;
}

function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}


var imgArr = new Array();
var initImg = function (obj){
    var imgs = $(obj).find("img");
    //console.log("123"+imgs.length);
    for (var i=0;i < imgs.length;i++){
        doSetTimeout(imgs,i);
    }
}

function doSetTimeout(imgs,i) {
    setTimeout(function() {
        console.log("i: "+i);
        $(imgs[i]).attr("src",imgArr[i]);
    }, 300*i);
}